import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入组件
import company from '../views/company'
import find from '../views/find'
import question from '../views/question'
import my from '../views/my'
import userInfo from '../views/userInfo'
import editInfo from '../views/editInfo'
import message from '../views/message'
import login from '../views/login'

// 导入提示框
import { Toast } from 'vant'

// 导入vuex
import store from '../store'

// token工具函数
import { getToken, removeToken } from '../utils/token'

// 导入用户信息接口
import { getUserInfo } from '../api/my'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/company'
  },
  {
    path: '/company',
    component: company,
    meta: { showTabber: true, title: '公司' }
  },
  {
    path: '/question',
    component: question,
    meta: { showTabber: true, title: '刷题' }
  },
  {
    path: '/find',
    component: find,
    meta: { showTabber: true, title: '发现' }
  },
  {
    path: '/my',
    component: my,
    meta: { showTabber: true, title: '我的', needLogin: true }
  },
  {
    path: '/userInfo',
    component: userInfo,
    meta: { title: '用户信息', needLogin: true }
  },
  {
    path: '/editInfo',
    component: editInfo,
    meta: { title: '修改信息', needLogin: true }
  },
  {
    path: '/message',
    component: message,
    meta: { title: '我的消息' }
  },
  {
    path: '/login',
    component: login,
    meta: { title: '登录' }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.needLogin === true) {
    if (store.state.isLogin === true) {
      next()
    } else {
      if (getToken()) {
        getUserInfo().then(res => {
          if (res.data.code === 200) {
            store.commit('CHANGEUSERINFO', res.data.data)
            store.commit('CHANGEISLOGIN', true)
            next()
          } else {
            removeToken()
            Toast('请先登录')
            next('/login')
          }
        })
      } else {
        Toast('请先登录')
        next('/login')
      }
    }
  } else {
    next()
  }
})

router.afterEach((to, from) => {
  document.title = to.meta.title
})

export default router
